<template>
  <el-dialog title="新增点位" :model-value="modelValue" width="500px" @close="commEvent.onClose">
    <el-form ref="formRef" :model="formValue" :rules="formRules" label-width="100">
      <el-form-item label="名称" prop="name">
        <el-input v-model="formValue.name" placeholder="请输入点位名称" />
      </el-form-item>
      <el-form-item label="点位标识符" prop="mark">
        <el-input v-model="formValue.mark" placeholder="请输入点位标识符" />
      </el-form-item>
      <el-form-item label="参数单位" prop="unit">
        <el-select v-model="formValue.unit" placeholder="请选择参数单位" filterable>
          <el-option
            v-for="(item, index) in units"
            :key="index"
            :label="`${item.label}(${item.value})`"
            :value="item.value || ''"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formValue.remark" type="textarea" :rows="3" placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="commEvent.onClose">取消</el-button>
      <el-button type="primary" @click="commEvent.onSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { nextTick, PropType, ref, watch } from "vue"
import { ElMessage, FormInstance, FormRules } from "element-plus"
import { addMeterPoint } from "@/api/modules/archive"
import { SystemSpace } from "@/api/interface/archive"
import { EnumProps } from "@/components/ProTable/interface"

const props = defineProps({
  modelValue: Boolean,
  meterId: Number,
  units: { type: Array as PropType<EnumProps[]>, default: () => [] }
})
const emit = defineEmits(["update:modelValue", "refresh"])
// 参数
const formRef = ref<FormInstance>() // 表单实例
// 表单参数
const formValue = ref({ name: "", mark: "", unit: "", remark: "" })
// 表单校验
const formRules: FormRules = {
  name: [{ required: true, message: "请输入名称", trigger: "blur" }],
  mark: [
    { required: true, message: "请输入点位标识符", trigger: "blur" },
    { pattern: /^([A-Z]{3})_(CT|CL|AL)_([A-Z0-9]{3,4})$/, message: "点位标识符输入有误" }
  ],
  unit: [{ required: true, message: "请选择参数单位", trigger: "blur" }]
}
// 事件
const commEvent = {
  // 关闭弹窗
  onClose: () => {
    emit("update:modelValue", false)
  },
  // 提交表单
  onSubmit: () => {
    if (!formRef.value) return
    formRef.value.validate(async valid => {
      if (!valid) return
      const params: SystemSpace.AddMeterPoint = { ...formValue.value, meterId: props.meterId || 0 }
      const { code } = await addMeterPoint(params)
      if (code !== "200") return
      ElMessage.success("新增成功")
      commEvent.onClose()
      emit("refresh")
    })
  }
}
watch(
  () => props.modelValue,
  flag => {
    if (flag) {
      nextTick(() => {
        formRef.value?.resetFields()
      })
    }
  }
)
</script>

<style scoped></style>
